import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:custom_platform_device_id/platform_device_id.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../model/create_room_call_back.dart';
import '../util/consumable_store.dart';

class MemberCenterPage extends StatefulWidget {
  @override
  _MemberCenterPageState createState() => _MemberCenterPageState();
}

final bool _kAutoConsume = Platform.isIOS || true;

const List<String> _kProductIds = <String>[
  "heart_month_vip",
  "heart_year_vip",
  "heart_forever_vip",
];

class _MemberCenterPageState extends State<MemberCenterPage> {
  int selectedIndex = 2; // 默认选中永久买断

  List<String> membershipTypes = [
    '月度会员',
    '年度会员',
    '永久会员',
  ];

  List<String> membershipDescriptions = [
    '灵活选择，轻松体验',
    '超值优惠，尊享全年',
    '一次购买，永久尊享',
  ];

  List<double> membershipPrices = [
    18.0,
    98.0,
    188.0,
  ];

  List<double> membershipOriginalPrices = [
    30.0,
    128.0,
    258.0,
  ];

  List<String> privileges = [
    '无限次与AI对话交流',
    '解锁所有角色和场景',
    '专属高级提示词库',
    '优先获取新功能体验',
    '专属客服支持',
  ];

  List<IconData> privilegeIcons = [
    Icons.chat_bubble_outline,
    Icons.people_outline,
    Icons.lightbulb_outline,
    Icons.new_releases_outlined,
    Icons.support_agent,
  ];

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<String> _notFoundIds = <String>[];
  List<ProductDetails> _products = <ProductDetails>[];
  List<PurchaseDetails> _purchases = <PurchaseDetails>[];
  List<String> _consumables = <String>[];
  bool _isAvailable = false;
  bool _purchasePending = false;
  bool _loading = true;
  String? _queryProductError;
  String currVipState = "当前非会员";
  String phone = "";

  @override
  Widget build(BuildContext context) {
    return OKToast(
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
          title: const Text('会员中心', style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontSize: 18,
          )),
          centerTitle: true,
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Color(0xFF6A88E6), Color(0xFF8A6AE6)],
              ),
            ),
          ),
          elevation: 0,
        ),
        body: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFFF8F9FF), Color(0xFFE8EFFE)],
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户当前状态卡片
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                child: Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 10,
                        offset: Offset(0, 4),
                      ),
                    ],
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [Color(0xFF6A88E6), Color(0xFF8A6AE6)],
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.stars_rounded, color: Colors.white, size: 24),
                      SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              currVipState,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                            SizedBox(height: 4),
                            Text(
                              '升级会员解锁全部特权',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white.withOpacity(0.9),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // 会员选择标题
              Padding(
                padding: const EdgeInsets.only(left: 20, top: 8, bottom: 16),
                child: Text(
                  '选择会员套餐',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                ),
              ),

              // 会员套餐选择
              SizedBox(
                height: 180,
                child: PageView.builder(
                  itemCount: membershipTypes.length,
                  controller: PageController(viewportFraction: 0.85),
                  onPageChanged: (index) {
                    setState(() {
                      selectedIndex = index;
                    });
                  },
                  itemBuilder: (context, index) {
                    return AnimatedScale(
                      duration: Duration(milliseconds: 300),
                      scale: selectedIndex == index ? 1.0 : 0.9,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            selectedIndex = index;
                          });
                        },
                        child: Container(
                          margin: EdgeInsets.symmetric(horizontal: 8, vertical: 12),
                          padding: EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black12,
                                blurRadius: 10,
                                offset: Offset(0, 4),
                              ),
                            ],
                            border: selectedIndex == index
                                ? Border.all(color: Color(0xFF6A88E6), width: 2)
                                : null,
                            gradient: selectedIndex == index
                                ? LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              colors: [Color(0xFFF1F6FF), Colors.white],
                            )
                                : null,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                children: [
                                  Text(
                                    membershipTypes[index],
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Color(0xFF333333),
                                    ),
                                  ),
                                  SizedBox(height: 4),
                                  Text(
                                    membershipDescriptions[index],
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Color(0xFF666666),
                                    ),
                                  ),
                                ],
                              ),
                              Column(
                                children: [
                                  Text(
                                    '￥${membershipPrices[index]}',
                                    style: TextStyle(
                                      fontSize: 24,
                                      fontWeight: FontWeight.bold,
                                      color: Color(0xFF6A88E6),
                                    ),
                                  ),
                                  Text(
                                    '原价: ￥${membershipOriginalPrices[index]}',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey,
                                      decoration: TextDecoration.lineThrough,
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                  color: selectedIndex == index
                                      ? Color(0xFF6A88E6).withOpacity(0.1)
                                      : Colors.grey.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(20),
                                ),
                                child: Text(
                                  selectedIndex == index ? '已选择' : '点击选择',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: selectedIndex == index
                                        ? Color(0xFF6A88E6)
                                        : Colors.grey,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),

              // 会员特权标题
              Padding(
                padding: const EdgeInsets.only(left: 20, top: 24, bottom: 16),
                child: Text(
                  '会员专属特权',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                ),
              ),

              // 会员特权列表
              Expanded(
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 10,
                        offset: Offset(0, 4),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(16),
                    child: ListView.separated(
                      padding: EdgeInsets.all(16),
                      itemCount: privileges.length,
                      separatorBuilder: (context, index) => Divider(height: 20, color: Colors.grey[100]),
                      itemBuilder: (context, index) {
                        return ListTile(
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                          leading: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: Color(0xFF6A88E6).withOpacity(0.1),
                              shape: BoxShape.circle,
                            ),
                            child: Icon(privilegeIcons[index], color: Color(0xFF6A88E6)),
                          ),
                          title: Text(
                            privileges[index],
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          trailing: Icon(Icons.check_circle, color: Color(0xFF6A88E6)),
                        );
                      },
                    ),
                  ),
                ),
              ),

              // 按钮区域
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    // 立即购买按钮
                    AnimatedContainer(
                      duration: Duration(milliseconds: 300),
                      width: double.infinity,
                      height: 54,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: Color(0xFF6A88E6).withOpacity(0.4),
                            blurRadius: 10,
                            offset: Offset(0, 4),
                          ),
                        ],
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [Color(0xFF6A88E6), Color(0xFF8A6AE6)],
                        ),
                      ),
                      child: TextButton(
                        onPressed: () async {
                          if (Platform.isIOS) {
                            final text = await showTextInputDialog(
                              context: context,
                              textFields: [
                                DialogTextField(
                                  hintText: '请输入您的手机号',
                                  maxLength: 11,
                                  keyboardType: TextInputType.phone,
                                ),
                              ],
                              title: '绑定手机号',
                              message: '绑定手机号后，您可以在更换设备时恢复会员权益',
                              cancelLabel: '取消',
                              okLabel: '确定',
                            );
                            if (text != null && text.isNotEmpty && text[0].isNotEmpty) {
                              phone = text[0];
                              postIosPay();
                            } else if (text != null && text[0].isEmpty) {
                              showToast("请输入有效的手机号");
                            }
                          } else {
                            showToast("安卓端支付即将上线，敬请期待");
                          }
                        },
                        style: TextButton.styleFrom(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        child: Text(
                          '立即开通',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 12),

                    // 恢复购买按钮
                    OutlinedButton(
                      onPressed: () async {
                        final text = await showTextInputDialog(
                          context: context,
                          textFields: [
                            DialogTextField(
                              hintText: '请输入您绑定的手机号',
                              maxLength: 11,
                              keyboardType: TextInputType.phone,
                            ),
                          ],
                          title: '恢复会员',
                          message: '请输入您购买时绑定的手机号以恢复会员权益',
                          cancelLabel: '取消',
                          okLabel: '确定',
                        );
                        if (text != null && text.isNotEmpty && text[0].isNotEmpty) {
                          resumeVip(text[0]);
                        } else if (text != null && text[0].isEmpty) {
                          showToast("请输入有效的手机号");
                        }
                      },
                      style: OutlinedButton.styleFrom(
                        backgroundColor: Colors.white,
                        foregroundColor: Color(0xFF6A88E6),
                        side: BorderSide(color: Color(0xFF6A88E6)),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        minimumSize: Size(double.infinity, 54),
                      ),
                      child: Text(
                        '恢复购买',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),

                    SizedBox(height: 8),

                    // 服务协议提示
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: Text(
                        '开通即代表同意《会员服务协议》和《隐私政策》',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 其他方法保持不变...
  void resumeVip(String phone) async {
    try {
      EasyLoading.show();
      Response response;
      String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
      var formData = FormData.fromMap({
        'phone': phone,
        'userId': deviceId,
      });
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 15000),
          receiveTimeout: const Duration(seconds: 15000),
          responseType: ResponseType.plain);
      Dio dio = Dio(baseOptions);
      response = await dio.post(
          "https://miusi.tripcan.cn/v1/resumeVip.php",
          data: formData);
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack callBack = CreateRoomCallBack.fromJson(respMap); //转成json对象数组
      EasyLoading.dismiss();
      if (callBack.status == 1) {
        showToast("恢复成功");
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 1);
        prefs.setInt("isResumeVip", 1);
        getVipInfo();
      } else {
        showToast(callBack.message);
      }
    } catch (error) {
      showToast("服务器错误,请稍后");
    }
  }

  void getVipInfo() async {
    EasyLoading.show(status: '加载中...');
    try {
      String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
      Response response;
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 15000),
          receiveTimeout: const Duration(seconds: 15000),
          responseType: ResponseType.plain);
      Dio dio = Dio(baseOptions);
      response = await dio
          .get("https://miusi.tripcan.cn/v1/getVipInfo.php?userId=$deviceId");
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack callBack = CreateRoomCallBack.fromJson(respMap); //转成json对象数组
      if (callBack.status == 1) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 1);
        setState(() {
          if(callBack.data=="2"){
            currVipState = "永久会员 · 尊享全部特权";
          }else if(callBack.data=="1"){
            currVipState = "年度会员 · 尊享全部特权";
          }else if(callBack.data=="0"){
            currVipState = "月度会员 · 尊享全部特权";
          }else{
            currVipState = "当前非会员";
          }
        });
      }else{
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 0);
        setState(() {
          currVipState = "当前非会员";
        });
      }
    } catch (error) {}
    EasyLoading.dismiss();
  }

  void postIosPay() async {
    showToast("开始购买...");
    late PurchaseParam purchaseParam;
    for (int i = 0; i < _products.length; i++) {
      if (_products[i].id == _kProductIds[selectedIndex]) {
        purchaseParam = PurchaseParam(
          productDetails: _products[i],
        );
        break;
      }
    }
    _inAppPurchase.buyConsumable(
        purchaseParam: purchaseParam, autoConsume: _kAutoConsume);
  }

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      final Stream<List<PurchaseDetails>> purchaseUpdated =
          _inAppPurchase.purchaseStream;
      _subscription =
          purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
            _listenToPurchaseUpdated(purchaseDetailsList);
          }, onDone: () {
            _subscription.cancel();
          }, onError: (Object error) {
            // handle error here.
          });
      initStoreInfo();
    }
    getVipInfo();
  }

  Future<void> initStoreInfo() async {
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      EasyLoading.dismiss();
      setState(() {
        _isAvailable = isAvailable;
        _products = <ProductDetails>[];
        _purchases = <PurchaseDetails>[];
        _notFoundIds = <String>[];
        _consumables = <String>[];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
      _inAppPurchase
          .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    final ProductDetailsResponse productDetailResponse =
    await _inAppPurchase.queryProductDetails(_kProductIds.toSet());
    if (productDetailResponse.error != null) {
      EasyLoading.dismiss();
      setState(() {
        _queryProductError = productDetailResponse.error!.message;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _purchases = <PurchaseDetails>[];
        _notFoundIds = productDetailResponse.notFoundIDs;
        _consumables = <String>[];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    if (productDetailResponse.productDetails.isEmpty) {
      EasyLoading.dismiss();
      setState(() {
        _queryProductError = null;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _purchases = <PurchaseDetails>[];
        _notFoundIds = productDetailResponse.notFoundIDs;
        _consumables = <String>[];
        _purchasePending = false;
        _loading = false;
      });
      return;
    }

    final List<String> consumables = await ConsumableStore.load();
    setState(() {
      _isAvailable = isAvailable;
      _products = productDetailResponse.productDetails;
      _notFoundIds = productDetailResponse.notFoundIDs;
      _consumables = consumables;
      _purchasePending = false;
      _loading = false;
    });

    final Map<String, PurchaseDetails> purchases =
    Map<String, PurchaseDetails>.fromEntries(
        _purchases.map((PurchaseDetails purchase) {
          if (purchase.pendingCompletePurchase) {
            _inAppPurchase.completePurchase(purchase);
          }
          return MapEntry<String, PurchaseDetails>(purchase.productID, purchase);
        }));

    EasyLoading.dismiss();
  }

  @override
  void dispose() {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
      _inAppPurchase
          .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
      _subscription.cancel();
    }
    super.dispose();
  }

  Future<void> consume(String id) async {
    await ConsumableStore.consume(id);
    final List<String> consumables = await ConsumableStore.load();
    setState(() {
      _consumables = consumables;
    });
  }

  void showPendingUI() {
    setState(() {
      _purchasePending = true;
    });
  }

  Future<void> deliverProduct(PurchaseDetails purchaseDetails) async {
    await ConsumableStore.save(purchaseDetails.purchaseID!);
    final List<String> consumables = await ConsumableStore.load();
    setState(() {
      _purchasePending = false;
      _consumables = consumables;
    });
  }

  void handleError(IAPError error) {
    setState(() {
      _purchasePending = false;
    });
  }

  Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    EasyLoading.show(status: '加载中...');
    try {
      Response response;
      String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
      var formData = FormData.fromMap({
        'receipt': purchaseDetails.verificationData.serverVerificationData,
        'userId': deviceId,
        'vipType': selectedIndex,
        'phone': phone
      });
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 15),
          receiveTimeout: const Duration(seconds: 15),
          responseType: ResponseType.plain);
      Dio dio = Dio(baseOptions);
      response = await dio.post(
          "https://miusi.tripcan.cn/v1/vertifyIosPay.php",
          data: formData);
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack callBack = CreateRoomCallBack.fromJson(respMap); //转成json对象数组
      EasyLoading.dismiss();
      if (callBack.status == 1) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 1);
        getVipInfo();
        return Future<bool>.value(true);
      } else {
        return Future<bool>.value(false);
      }
    } catch (error) {}
    return Future<bool>.value(true);
  }

  void _handleInvalidPurchase(PurchaseDetails purchaseDetails) {
    // handle invalid purchase here if  _verifyPurchase` failed.
  }

  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        showPendingUI();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          handleError(purchaseDetails.error!);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          final bool valid = await _verifyPurchase(purchaseDetails);
          if (valid) {
            deliverProduct(purchaseDetails);
            getVipInfo();
          } else {
            _handleInvalidPurchase(purchaseDetails);
            return;
          }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    }
  }

  Future<void> confirmPriceChange(BuildContext context) async {
    // if (Platform.isIOS) {
    //   final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition =
    //   _inAppPurchase
    //       .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
    //   await iapStoreKitPlatformAddition.showPriceConsentIfNeeded();
    // }
  }
}

class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}